package com.uptown.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;

/**
 * @author: Lixiaofei
 * @date: 2020/5/12 16:43
 */
public class NIOServer {

    public static void main(String[] args) throws IOException {
        //创建ServerSocketChannel  -> ServerScoket
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        Selector selector = Selector.open();
        //绑定端口
        serverSocketChannel.socket().bind(new InetSocketAddress(6666));
        //设置非阻塞
        serverSocketChannel.configureBlocking(false);
        //把serverSocketChannel关心事件为OP_Accept
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        //循环等待客户端连接
        while (true){
            if(selector.select(1000) == 0){//没有事件发生
                System.out.println("服务器等待了1s，无连接");
                continue;
            }
            //如果返回的>0   获取到相关的selectionKey集合
            //有事件发生的Selector
            //通过selectionkey拿到通道
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            //遍历
            Iterator<SelectionKey> keyIterator = selectionKeys.iterator();
            while(keyIterator.hasNext()){
                //获取到selectionkey
                SelectionKey selectionKey = keyIterator.next();
                //根据key对应的通道发生的事件做相应的处理
                if(selectionKey.isAcceptable()){ //有客户端来连接
                   //生成给该客户端生成scoketChannel
                    SocketChannel clientAccept = serverSocketChannel.accept();
                    System.out.println("客户端连接成功 生成一个SocketChannel"+clientAccept.hashCode());
                    //将当前channel也注册到selector  关注事件为OP_READ
                    // 同时给channel关联一个buffer
                    clientAccept.configureBlocking(false);
                    clientAccept.register(selector,SelectionKey.OP_READ,ByteBuffer.allocate(1024));
                }
                if(selectionKey.isReadable()){
                    //通过key 反向获取channel
                    SocketChannel channel = (SocketChannel)selectionKey.channel();
                    System.out.println("接受服务端channel"+channel.hashCode());
                    //获取channel关联的buffer
                    ByteBuffer buffer = (ByteBuffer)selectionKey.attachment();
                    int read = channel.read(buffer);
                    if(read > 0){
                        System.out.println("from 客户端"+ new String(buffer.array()));
                    }else {
                        System.out.println("客户端关闭");
                        channel.close();
                    }
                }
                //手动从集合中移除当前selectionkey，防止重复操作
                keyIterator.remove();
            }
        }
    }
}
